package com.dorso.service;

import com.dorso.dao.ProductRepository;
import com.dorso.entity.Product;
import com.dorso.exception.ProductAdminException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Autowired
    ProductRepository productRepository;


//    private Map<Long, Product> productMap =
//            Collections.synchronizedMap(new HashMap<Long, Product>());

    //添加商品
    public Product addProduct(Product product) throws ProductAdminException {
        if (product.getId() != null) {
            if (productRepository.findById(product.getId()).isPresent()) {
                throw new ProductAdminException("添加商品失败：商品已经存在");
            }
        }
        return productRepository.save(product);
    }

    //根据id查找
    public Product getProduct(long id) {
//        return productMap.get(id);
        return productRepository.findById(id).get();
    }
    //更新产品信息
    public void updateProduct(long id,Product product)throws ProductAdminException{
//        Product product1=productMap.get(id);
//        if(product1!=null){
//            productMap.put(product.getId(),product);
//        }
        if(!productRepository.findById(id).isPresent()){
            throw new ProductAdminException("产品信息更新失败，输入的id号"+id+"不存在");
        }
        productRepository.saveAndFlush(product);
    }
    //删除产品
    public void deleteProduct(long id){
//        productMap.remove(id);
        productRepository.deleteById(id);

    }
//    public void deleteAll(){
////        productMap.clear();
//    }
}